<?php
/**
 *
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2018/6/6 9:41
 * @copyright PanxSoft Inc.
 */

namespace App\Services\Presenters\Admin;


use App\Http\Controllers\Admin\Customer\WechatUserController;
use App\Models\Panx\SkinDetector;
use App\Models\Store\HmSkinRecord;
use App\Models\Store\SkinRecord;
use App\Services\Presenters\HmSkinData;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Collection as BaseCollection;

class HmSkinRecordPresenter
{
    /**
     * 指定店铺的 微信用户的 会美检测仪的 肤质数据 统计数据
     * 附加微信用户反查的筛选条件
     *
     * @param array $store_ids
     *
     * @param $customer_id
     * @return array
     */
    public static function storesUsersStatisticLabelGroupData(array $store_ids, $customer_id): array
    {
        /** @var Collection $latest_skin_records */
        $latest_skin_records = SkinRecord::latestStoresWechatUsersTypeSkinRecords(
            $store_ids, SkinDetector::ID_HM
        );

        $skin_record_ids = $latest_skin_records->pluck('id')->all();

        /** @var Collection $hm_skin_records */
        $hm_skin_records = (new HmSkinRecord)
            ->whereIn('skin_record_id', $skin_record_ids)
            ->orderBy('position', 'asc')
            ->get();

        $position_groups = $hm_skin_records->groupBy('position');

        $position_counts = $position_groups
            ->map(function (Collection $hm_skin_records) {
                return $hm_skin_records->count();
            });

        $pos_oil_label_counts = $position_groups
            ->map(function (Collection $hm_skin_records) use($customer_id){
                return $hm_skin_records
                    ->groupBy(function (HmSkinRecord $record) use($customer_id){
//                        return HmSkinData::transScoreTitle('oil', $record->oil);
                        return HmSkinData::transScoreTitleByCustom(HmSkinData::HM_OIL, $record->oil, $customer_id);
                    })
                    ->transform(function (Collection $oil_group) {
                         return self::assembleLabelGroupData($oil_group, 'oil');
                    });
            });

        $pos_water_label_counts = $position_groups
            ->map(function (Collection $hm_skin_records) use($customer_id){
                return $hm_skin_records
                    ->groupBy(function (HmSkinRecord $record) use($customer_id){
//                        return HmSkinData::transScoreTitle('water', $record->water);
                        return HmSkinData::transScoreTitleByCustom(HmSkinData::HM_WATER, $record->oil, $customer_id);
                    })
                    ->transform(function (Collection $water_group) {
                         return self::assembleLabelGroupData($water_group, 'water');
                    });
            });

        $pos_flex_label_counts = $position_groups
            ->map(function (Collection $hm_skin_records) use($customer_id){
                return $hm_skin_records
                    ->groupBy(function (HmSkinRecord $record) use($customer_id){
//                        return HmSkinData::transScoreTitle('flex', $record->flex);
                        return HmSkinData::transScoreTitleByCustom(HmSkinData::HM_FLEX, $record->oil, $customer_id);
                    })
                    ->transform(function (Collection $flex_group) {
                        return self::assembleLabelGroupData($flex_group, 'flex');
                    });
            });

        $flex_counts = self::transformPositionItemLabelCounts($pos_flex_label_counts);
        $water_counts = self::transformPositionItemLabelCounts($pos_water_label_counts);
        $oil_counts = self::transformPositionItemLabelCounts($pos_oil_label_counts);

        return compact(
            'position_counts',
            'pos_flex_label_counts',
            'pos_oil_label_counts',
            'pos_water_label_counts',

            'flex_counts',
            'water_counts',
            'oil_counts'
        );
    }

    /**
     * 返回前端这样的数据才能通过饼图点击反查搜索对应的用户数据列表
     *
     * @used-by WechatUserController::reverseFilterHmLabelWxUsers()
     *
     * @param Collection|HmSkinRecord[] $label_group
     * @param string $column
     *
     * @return array
     */
    public static function assembleLabelGroupData(Collection $label_group, string $column): array
    {
        /** @var HmSkinRecord $hmSkinRecord */
        $hmSkinRecord = $label_group->first();

        return [
            'label_key' => self::assembleHmLabelKey($hmSkinRecord, $column),
            'count'     => $label_group->count(),
        ];
    }

    /**
     * 前端点击后饼图使用 label_key 做查询参数
     * @uses HmSkinData::flexLabelWhereRange() - 等返回 where 条件
     *
     *
     * @param HmSkinRecord $record
     * @param string $column
     *
     * @return string
     */
    public static function assembleHmLabelKey(HmSkinRecord $record,
                                              string $column): string
    {
        return $column.'_label_'.HmSkinData::hmItemLevelSort(array_search($column, HmSkinData::HM_ITEM_NAME_MAP), $record->{$column});
//        switch ($column) {
//            case 'water' :
//                return 'water_label_'.HmSkinData::hmItemLevelSort(HmSkinData::HM_WATER, $record->water);
//            case 'oil' :
//                return 'oil_label_'.HmSkinData::hmItemLevelSort(HmSkinData::HM_OIL, $record->oil);
//            case 'flex' :
//                return 'flex_label_'.HmSkinData::hmItemLevelSort(HmSkinData::HM_FLEX, $record->flex);
//            default :
//                throw new \InvalidArgumentException('error column');
//        }
    }

    /**
     * 把检查项目统计的数据结构从
     *      [
     *          测肤位置 n => [
     *              结果标签 n => [
     *                  label_key => 反查标签，
     *                  count => 数量
     *              ], ...
     *          ], ...
     *      ]
     * 转成
     *      item_counts = [
     *          [
     *              position => 位置，
     *              label_counts: [
     *                  [
     *                      label => 结果标签，
     *                      label_key => 反查标签，
     *                      count => 数量，
     *                  ],
     *                  其他标签...
     *              ]
     *          ],
     *          其他位置...
     *      ]
     *
     * @param $pos_item_label_counts
     *
     * @return Collection
     */
    private static function transformPositionItemLabelCounts(BaseCollection $pos_item_label_counts): BaseCollection
    {
        $item_counts = collect(HmSkinRecord::ALL_POSITIONS)
            // 这里是要求必须 返回所有位置的数据， 哪怕是空的，对应位置也要返回前端
            ->map(function (int $position) use ($pos_item_label_counts) {
                $label_counts = $pos_item_label_counts
                        ->get($position, collect()) // 找对应的 position, 如果没有直接返回 []
                        ->map(function (array $label_key_count, string $label) {
                            return $label_key_count + compact('label');
                        })
                        ->values();

                return compact('label_counts', 'position');
            });

        return $item_counts;
    }
}